//
//  WmcBaseWatermarkView.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/7.
//

import CoreLocation
import UIKit
import YPBedrock

// MARK: - [WmcBaseWatermarkTemplateView]

public extension WmcBaseWatermarkTemplateView {
    /// 展示模式
    enum StyleMode {
        /// 动态渲染
        case dynamicDraw

        /// 静态渲染
        case staticDraw

        /// 动态编辑渲染
        case dynamicEdit

        /// 静态编辑渲染
        case staticEdit

        /// 是否是静态
        var isStatic: Bool {
            switch self {
            case .dynamicDraw,
                 .dynamicEdit:
                return false
            case .staticDraw,
                 .staticEdit:
                return true
            }
        }
        
        /// 是否是编辑
        var isEdit: Bool {
            switch self {
            case .dynamicDraw,
                 .staticDraw:
                return false
            case .dynamicEdit,
                 .staticEdit:
                return true
            }
        }
    }
}

// MARK: - [WmcBaseWatermarkTemplateView]

/// 基类模板视图
open class WmcBaseWatermarkTemplateView: WmcBaseView {
    // Lifecycle

    deinit {
        WmcLogManager.DebugLog(type: .delloc, log: "水印模版对象被释放\(self)")
    }

    // Open

    /// 配置
    override open func config() {
        backgroundColor = .clear
    }

    // Internal

    /// 默认宽度
    var defaultWidth: CGFloat?

    /// 四周补偿距离（用于虚线框和拖动时的边界判断）
    var edgeCompensateDistance: UIEdgeInsets = .zero

    /// 展示模式
    var styleMode: StyleMode = .dynamicDraw

    /// 背景颜色视图
    lazy var backgroundColorView: UIView = {
        let view = UIView()
        return view
    }()

    /// 堆栈布局
    lazy var stackView: UIStackView = {
        let view = UIStackView()
        view.layer.cornerRadius = 4
        view.layer.masksToBounds = true
        return view
    }()

    /// 认证视图
    lazy var certificationView: WmcCertificationView = {
        let view = WmcCertificationView()
        return view
    }()

    /// 标题
    lazy var titleLabel: UILabel = {
        let label = UILabel.YP.Create(font: 14.yp.uiFont(weight: .medium), color: UIColor.white, alignment: .center)
        return label
    }()

    /// 副标题
    lazy var subTitleLabel: UILabel = {
        let label = UILabel.YP.Create(font: 14.yp.uiFont(weight: .medium), color: UIColor.white, alignment: .left)
        return label
    }()

    /// 时间
    lazy var timeLabel: WmcDateLabel = {
        let label = WmcDateLabel.YP.Create(font: 12.wmc_font,
                                           color: UIColor.white,
                                           alignment: .left)
        return label
    }()

    /// 遮罩切圆角
    lazy var maskLayer: CAShapeLayer = {
        let maskLayer = CAShapeLayer()
        return maskLayer
    }()

    /// 水印模型
    var watermarkModel: WmcWatermarkDetailModel?

    /// 配置品牌图回调
    var configOptionBrandBlock: YPBlock.OneParam<WmcWatermarkOptionModel>?

    /// 移除品牌图回调
    var removeBrandBlock: YPBlock.Empty?

    /// 内容视图缓存表
    var contentViewCacheMaps: [String: UIView] = [:]

    /// 编辑预览页是否展示外部的品牌图
    var editPreviewBrandContentShowBrand: Bool = true

    /// 是否展示认证水印
    var isShowCertificationWatermark: Bool = true

    /// 配置水印模型，进行渲染数据
    func configWatermarkModel(_ watermarkModel: WmcWatermarkDetailModel,
                              styleMode: WmcBaseWatermarkTemplateView.StyleMode)
    {
        self.watermarkModel = watermarkModel
        // 设置认证视图，子类可以自定义
        configWatermarkCertification(watermarkModel)
        // 设置缩放可以子类进行，每个水印的缩放不同
        let scale = watermarkModel.scaleSize.info.scale
        configWatermarkScale(scale)
        // 设置透明需要子类进行，每个水印的透明度不同
        let alpha = watermarkModel.alpha
        configWatermarkAlpha(alpha)
    }

    /// 配置认证视图
    func configWatermarkCertification(_ watermarkModel: WmcWatermarkDetailModel) {
        // 设置文案
        var isOpenTime: Bool = false
        var isOpenLocat: Bool = false
        watermarkModel.fields.forEach { op in
            if op.fieldType == .time {
                isOpenTime = op.isOpen
            }
            if op.fieldType == .addr {
                isOpenLocat = op.isOpen
            }
        }
        certificationView.isOpenTime = isOpenTime
        certificationView.isOpenLocat = isOpenLocat
        certificationView.staticAddressModel = watermarkModel.staticData.drawStaticAddress
        certificationView.styleMode = styleMode
        certificationView.showText()
    }

    /// 配置缩放
    func configWatermarkScale(_ scale: CGFloat) {
        // 设置大小
        transform = CGAffineTransform.YP.CreateScale(scale)
    }

    /// 配置透明度
    func configWatermarkAlpha(_ alpha: Int) {}

    /// 配置品牌图
    func configOptionBrand(_ optionBrand: WmcWatermarkOptionModel) {
        configOptionBrandBlock?(optionBrand)
    }

    /// 布局
    func makeConstraints() {
        if isShowCertificationWatermark {
            addSubview(certificationView)
            certificationView.snp.remakeConstraints { make in
                make.bottom.equalToSuperview().offset(-4)
                make.left.equalTo(0)
                make.right.equalToSuperview()
                make.height.equalTo(15)
            }
        }
    }

    /// 移除品牌图
    func removeBrand() {
        removeBrandBlock?()
    }

    /// 设置全屏水印
    func createFullScreenViews() -> [UIView] { return [] }

    /// 布局全屏水印
    func makeFullScreenViews(makeView: UIView, superView: WmcWatermarkContentView) {}

    /// 设置视图阴影
    func setShadow(_ view: UIView, color: UIColor = .wmc_grayH5_606066) {
        view.layer.shadowColor = color.cgColor
        view.layer.shadowRadius = 4
        view.layer.shadowOffset = CGSize(width: 0, height: 1)
        view.layer.shadowOpacity = 0.8
    }

    /// 计算透明度
    func calculateAlpha(_ alpha: Int, min: CGFloat = 0, max: CGFloat = 1) -> CGFloat {
        let length = (max - min)
        let alphaPercentage = (alpha.yp.cgFloat / 100)
        let alpha = alphaPercentage * length + min
        return (1 - alpha)
    }

    /// 切圆角
    func roundedRect(_ rect: CGRect, corners: UIRectCorner, cornerRadii: CGFloat){
        let maskPath = UIBezierPath(roundedRect: rect,
                                    byRoundingCorners: corners,
                                    cornerRadii: cornerRadii.yp.cgSize)
        maskLayer.path = maskPath.cgPath
        maskLayer.frame = bounds
        layer.mask = maskLayer
    }
}

// MARK: - Item创建方法

extension WmcBaseWatermarkTemplateView {
    /// 创建速度类型的视图
    func createSpeedItem(option: WmcWatermarkOptionModel,
                         styleMode: WmcBaseWatermarkTemplateView.StyleMode,
                         staticLocation: CLLocation?,
                         titleStyle: WmcDrawTitleContentItem.TitleStyle? = nil,
                         font: YPUnifiedFont = 14,
                         color: YPUnifiedColor? = nil,
                         maxTitleCount: Int? = nil,
                         speedFormat: WmcSpeedLabel.Format) -> WmcDrawTitleContentItem
    {
        let item = createTitleStyleContentTypeItem(option: option,
                                                   titleStyle: titleStyle,
                                                   font: font,
                                                   color: color,
                                                   maxTitleCount: maxTitleCount,
                                                   contentType: .speed(format: speedFormat))
        item.speedLabel.styleMode = styleMode
        if let staticLocation = staticLocation, styleMode.isStatic {
            item.speedLabel.updateLocation(staticLocation)
        }
        return item
    }

    /// 创建分贝类型的视图
    func createDecibeItem(option: WmcWatermarkOptionModel,
                          styleMode: WmcBaseWatermarkTemplateView.StyleMode,
                          titleStyle: WmcDrawTitleContentItem.TitleStyle? = nil,
                          font: YPUnifiedFont = 14,
                          color: YPUnifiedColor? = nil,
                          maxTitleCount: Int? = nil,
                          decibeFormat: WmcDecibeLabel.Format) -> WmcDrawTitleContentItem
    {
        let item = createTitleStyleContentTypeItem(option: option,
                                                   titleStyle: titleStyle,
                                                   font: font,
                                                   color: color,
                                                   maxTitleCount: maxTitleCount,
                                                   contentType: .decibe(format: decibeFormat))
        item.decibeLabel.styleMode = styleMode
        return item
    }

    /// 创建方位角类型的视图
    func createAzimuthItem(option: WmcWatermarkOptionModel,
                           styleMode: WmcBaseWatermarkTemplateView.StyleMode,
                           staticAzimuth: Double?,
                           titleStyle: WmcDrawTitleContentItem.TitleStyle? = nil,
                           font: YPUnifiedFont = 14,
                           color: YPUnifiedColor? = nil,
                           maxTitleCount: Int? = nil,
                           azimuthFormat: WmcAzimuthAngleLabel.Format) -> WmcDrawTitleContentItem
    {
        let item = createTitleStyleContentTypeItem(option: option,
                                                   titleStyle: titleStyle,
                                                   font: font,
                                                   color: color,
                                                   maxTitleCount: maxTitleCount,
                                                   contentType: .azimuthAngle(format: azimuthFormat))
        item.azimuthAngleLabel.styleMode = styleMode
        if let staticAzimuth = staticAzimuth, styleMode.isStatic {
            item.azimuthAngleLabel.updateAzimuthAngle(staticAzimuth)
        }
        return item
    }

    /// 创建海拔类型的视图
    func createAltitudeItem(option: WmcWatermarkOptionModel,
                            styleMode: WmcBaseWatermarkTemplateView.StyleMode,
                            staticLocation: CLLocation?,
                            titleStyle: WmcDrawTitleContentItem.TitleStyle? = nil,
                            font: YPUnifiedFont = 14,
                            color: YPUnifiedColor? = nil,
                            maxTitleCount: Int? = nil,
                            altitudeFormat: WmcAltitudeLabel.Format) -> WmcDrawTitleContentItem
    {
        let item = createTitleStyleContentTypeItem(option: option,
                                                   titleStyle: titleStyle,
                                                   font: font,
                                                   color: color,
                                                   maxTitleCount: maxTitleCount,
                                                   contentType: .altitude(format: altitudeFormat))
        item.altitudeLabel.styleMode = styleMode
        if let staticLocation = staticLocation, styleMode.isStatic {
            item.altitudeLabel.updateLocation(staticLocation)
        }
        return item
    }

    /// 创建天气类型的视图
    func createWeatherItem(option: WmcWatermarkOptionModel,
                           styleMode: WmcBaseWatermarkTemplateView.StyleMode,
                           staticWeater: WmcWeatherModel?,
                           titleStyle: WmcDrawTitleContentItem.TitleStyle? = nil,
                           font: YPUnifiedFont = 14,
                           color: YPUnifiedColor? = nil,
                           maxTitleCount: Int? = nil,
                           weatherFormat: WmcWeatherLabel.Format) -> WmcDrawTitleContentItem
    {
        let item = createTitleStyleContentTypeItem(option: option,
                                                   titleStyle: titleStyle,
                                                   font: font,
                                                   color: color,
                                                   maxTitleCount: maxTitleCount,
                                                   contentType: .weather(format: weatherFormat))
        item.weatherLabel.styleMode = styleMode
        if let staticWeater = staticWeater, styleMode.isStatic {
            item.weatherLabel.updateWeather(staticWeater)
        }
        return item
    }

    /// 创建定位地点类型的视图
    func createLocationItem(option: WmcWatermarkOptionModel,
                            styleMode: WmcBaseWatermarkTemplateView.StyleMode,
                            staticAddress: WmcSelectAddressModel?,
                            titleStyle: WmcDrawTitleContentItem.TitleStyle? = nil,
                            font: YPUnifiedFont = 14,
                            color: YPUnifiedColor? = nil,
                            maxTitleCount: Int? = nil,
                            locationFormat: WmcLocationLabel.Format) -> WmcDrawTitleContentItem
    {
        let item = createTitleStyleContentTypeItem(option: option,
                                                   titleStyle: titleStyle,
                                                   font: font,
                                                   color: color,
                                                   maxTitleCount: maxTitleCount,
                                                   contentType: .location(format: locationFormat))
        item.locationLabel.styleMode = styleMode
        if let staticAddress = staticAddress, styleMode.isStatic {
            item.locationLabel.updateLocation(staticAddress)
        }
        return item
    }

    /// 创建日期/时间类型的视图
    func createDateItem(option: WmcWatermarkOptionModel,
                        styleMode: WmcBaseWatermarkTemplateView.StyleMode,
                        staticDate: Date?,
                        titleStyle: WmcDrawTitleContentItem.TitleStyle? = nil,
                        font: YPUnifiedFont = 14,
                        color: YPUnifiedColor? = nil,
                        maxTitleCount: Int? = nil,
                        dateFormat: WmcDateLabel.Format) -> WmcDrawTitleContentItem
    {
        let item = createTitleStyleContentTypeItem(option: option,
                                                   titleStyle: titleStyle,
                                                   font: font,
                                                   color: color,
                                                   maxTitleCount: maxTitleCount,
                                                   contentType: .time(format: dateFormat))
        item.timeLabel.styleMode = styleMode
        if let staticDate = staticDate, styleMode.isStatic {
            item.timeLabel.updateDate(staticDate)
        }
        return item
    }

    /// 创建默认的文字内容类型的视图
    func createDefaultTextItem(option: WmcWatermarkOptionModel,
                               titleStyle: WmcDrawTitleContentItem.TitleStyle? = nil,
                               font: YPUnifiedFont = 14,
                               color: YPUnifiedColor? = nil,
                               maxTitleCount: Int? = nil,
                               text: String? = nil) -> WmcDrawTitleContentItem
    {
        var _text = option.drawContentText()
        if let text = text {
            _text = text
        }
        let item = createTitleStyleContentTypeItem(option: option,
                                                   titleStyle: titleStyle,
                                                   font: font,
                                                   color: color,
                                                   maxTitleCount: maxTitleCount,
                                                   contentType: .content(text: _text))
        return item
    }

    /// 创建标题内容类型的视图
    func createTitleStyleContentTypeItem(option: WmcWatermarkOptionModel,
                                         titleStyle: WmcDrawTitleContentItem.TitleStyle? = nil,
                                         font: YPUnifiedFont = 14,
                                         color: YPUnifiedColor? = nil,
                                         maxTitleCount: Int? = nil,
                                         contentType: WmcDrawTitleContentItem.ContentType) -> WmcDrawTitleContentItem
    {
        var _titleStyle: WmcDrawTitleContentItem.TitleStyle = .title(option.title,
                                                                     maxTitleCount: maxTitleCount ?? option.title.count)
        if let titleStyle = titleStyle {
            _titleStyle = titleStyle
        }
        var _color = option.uiTextColor
        if let color = color {
            _color = UIColor.YP.Create(color)
        }
        let config: WmcDrawTitleContentItem.Config =
            .init(titleStyle: _titleStyle,
                  font: font,
                  color: _color,
                  contentType: contentType)
        let item = createTitleContentItem(key: "\(option.fieldId)\(option.label)\(option.title)",
                                          config: config)
        return item
    }

    /// 创建标题文字内容的视图
    func createTitleContentItem(key: String,
                                config: WmcDrawTitleContentItem.Config) -> WmcDrawTitleContentItem
    {
        if let titleContentItem = contentViewCacheMaps[key] as? WmcDrawTitleContentItem {
            titleContentItem.config = config
            titleContentItem.setContent()
            return titleContentItem
        } else {
            let item = WmcDrawTitleContentItem(config: config)
            contentViewCacheMaps[key] = item
            return item
        }
    }
}
